SUIPatternLibrary.Database = (function($){
var
    selectPatterns = function(callback){
        query("SELECT * FROM Pattern;", callback);
    },

    selectEngines = function(callback){
        query("SELECT * FROM Engines;", callback);
    },

    selectPatternsForEngine = function(engineName, callback){
        query("SELECT P.*, O.Left, O.Top, O.Width, O.Height, O.Selector " +
              "FROM Overlay AS O, Pattern AS P " +
              "WHERE O.EngineName='" + engineName + "' " +
              "AND P.Name=O.PatternName;", callback);
    },

    selectEnginesForPattern = function(patternName, callback){
        query("SELECT E.*, O.Left, O.Top, O.Width, O.Height " +
            "FROM Overlay AS O, Engines AS E " +
            "WHERE O.PatternName='" + patternName + "' " +
            "AND E.Name=O.EngineName;", callback);
    },

    selectRelatedPatternsForPattern = function(patternName, callback){
        query("SELECT RelatedPatternName AS Name FROM `RelatedPatterns` WHERE PatternName='" + patternName + "';", callback)
    },

    selectPrinciplesForPattern = function(patternName, callback){
        query("SELECT Principle FROM `Principles` WHERE PatternName='" + patternName + "';", callback)
    },

    toLowerCaseObjectProperties = function(obj){
        if(obj.length){
            for(var i = 0; i < obj.length; i++){
                obj[i] = toLowerCaseObjectProperties(obj[i]);
            }
            return obj;
        }
        var l = {};
        for(var key in obj){
            l[key.toLowerCase()] = obj[key];
        }
        return l;
    },

    query = function(query, callback){
        $.post("http://hijacksoft.de/tools/database_extension.php", { query : query }, function(data){
            try {
                data = JSON.parse(data);
            }
            catch (e){
                callback([data, e]);
                return;
            }
            callback(toLowerCaseObjectProperties(data));
        });
    };

    return {
        query : query,
        selectPatterns : selectPatterns,
        selectEngines : selectEngines,
        selectPatternsForEngine : selectPatternsForEngine,
        selectEnginesForPattern : selectEnginesForPattern,
        selectRelatedPatternsForPattern : selectRelatedPatternsForPattern,
        selectPrinciplesForPattern : selectPrinciplesForPattern
    }
    
}(jQuery));